package com.pms.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import com.pms.exception.AppException;

public class FtpTools {

	/**
	 * Description: 向FTP服务器上传文件
	 * 
	 * @param url
	 *            FTP服务器hostname
	 * @param port
	 *            FTP服务器端口
	 * @param username
	 *            FTP登录账号
	 * @param password
	 *            FTP登录密码
	 * @param remotePath
	 *            FTP服务器保存目录
	 * @param filename
	 *            上传到FTP服务器上的文件名
	 * @param input
	 *            输入流
	 * @throws AppException
	 */
	public static void uploadFile(String url, String port, String username, String password, String remotePath,
			String filename, FileInputStream input) throws AppException {

		FTPClient ftp = null;
		try {
			ftp = new FTPClient();
			ftp.setControlEncoding("UTF-8");
			ftp.setBufferSize(1024);
			// 连接FTP服务器
			try {
				ftp.connect(url, new Integer(port));
			} catch (Exception e) {
				throw new AppException("请求连接FTP服务失败!");
			}
			if (!ftp.isConnected()) {
				throw new AppException("连接FTP服务失败!");
			}
			// 登录
			if (!ftp.login(username, password)) {
				throw new AppException("帐号或密码错误,登录FTP失败!");
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
			ftp.enterLocalPassiveMode();

			if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
				ftp.disconnect();
				throw new AppException("连接FTP服务失败!");
			}
			if (!ftp.changeWorkingDirectory(remotePath)) {
				throw new AppException("FTP工作目录未找到!!");
			}
			if (!ftp.storeFile(filename, input)) {
				throw new AppException("FTP：storeFile 上传文件失败!");
			}
			input.close();
			ftp.logout();
		} catch (Exception e) {
			throw new AppException(e.getMessage());
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 数据文件同时伴生一个控制文件，控制文件的名字是数据文件名字+后缀 数据文件的名字是"_"分割的字段+".txt"||"xls",
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 * @param checkFileSuffix
	 * @return
	 * @throws AppException
	 */
	public static List<String> listAllTxtFile(String url, int port, String username, String password, String remotePath,
			String checkFileSuffix) throws AppException {

		List<String> listDatfile = new ArrayList<String>();

		FTPClient ftp = null;

		try {
			ftp = new FTPClient();
			ftp.setControlEncoding("UTF-8");
			ftp.setBufferSize(1024);
			// 连接FTP服务器
			try {
				ftp.connect(url, new Integer(port));
			} catch (Exception e) {
				throw new AppException("请求连接FTP服务失败!");
			}
			if (!ftp.isConnected()) {
				throw new AppException("连接FTP服务失败!");
			}
			// 登录
			if (!ftp.login(username, password)) {
				throw new AppException("帐号或密码错误,登录FTP失败!");
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
			ftp.enterLocalPassiveMode();

			if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
				ftp.disconnect();
				throw new AppException("连接FTP服务失败!");
			}
			if (!ftp.changeWorkingDirectory(remotePath)) {
				throw new AppException("FTP工作目录未找到!!");
			}

			FTPFile[] fs = ftp.listFiles();

			if (fs == null || fs.length < 1) {

				throw new AppException("检验文件不存在!");
			}

			for (int i = 0; i < fs.length; i++) {
				if (fs[i].getName().endsWith(".txt" + checkFileSuffix)) {
					listDatfile.add(fs[i].getName().replace(checkFileSuffix, ""));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new AppException(e.getMessage());
		} finally {
			try {
				ftp.logout();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return listDatfile;
	}
	
	public static List<String> listAllDatFile(String url, int port, String username, String password, String remotePath,
			String checkFileSuffix) throws AppException {
		List<String> listDatfile = new ArrayList<String>();
		FTPClient ftp = null;
		try {
			ftp = new FTPClient();
			ftp.setControlEncoding("UTF-8");
			ftp.setBufferSize(1024);
			// 连接FTP服务器
			try {
				ftp.connect(url, new Integer(port));
			} catch (Exception e) {
				throw new AppException("请求连接FTP服务失败!");
			}
			if (!ftp.isConnected()) {
				throw new AppException("连接FTP服务失败!");
			}
			// 登录
			if (!ftp.login(username, password)) {
				throw new AppException("帐号或密码错误,登录FTP失败!");
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
			ftp.enterLocalPassiveMode();

			if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
				ftp.disconnect();
				throw new AppException("连接FTP服务失败!");
			}
			if (!ftp.changeWorkingDirectory(remotePath)) {
				throw new AppException("FTP工作目录未找到!!");
			}

			FTPFile[] fs = ftp.listFiles();

			if (fs == null || fs.length < 1) {

				throw new AppException("检验文件不存在!");
			}
			for (int i = 0; i < fs.length; i++) {
				if (fs[i].getName().endsWith(".dat")) {
					listDatfile.add(fs[i].getName());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new AppException(e.getMessage());
		} finally {
			try {
				ftp.logout();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return listDatfile;
	}
	/**
	 * Description: 从FTP服务器下载文件
	 *
	 * @Version1.0
	 * 
	 * @param url
	 *            FTP服务器hostname
	 * @param port
	 *            FTP服务器端口
	 * @param username
	 *            FTP登录账号
	 * @param password
	 *            FTP登录密码
	 * @param remotePath
	 *            FTP服务器上的相对路径
	 * @param fileName
	 *            要下载的文件名
	 * @param localFTPPath
	 *            本地文件存放目录
	 * @param checkFile
	 *            下载前判断文件是否存在
	 * @return
	 */
	@SuppressWarnings("unused")
	public static void downFile(String url, int port, String username, String password, String remotePath,
			String checkFile, String fileName, String localFTPPath) throws AppException {

		FTPClient ftp = null;
		boolean retFlag = false;

		OutputStream outputStream = null;
		try {
			ftp = new FTPClient();
			ftp.setControlEncoding("UTF-8");
			ftp.setBufferSize(1024);
			// 连接FTP服务器
			try {
				ftp.connect(url, new Integer(port));
			} catch (Exception e) {
				throw new AppException("请求连接FTP服务失败!");
			}
			if (!ftp.isConnected()) {
				throw new AppException("连接FTP服务失败!");
			}
			// 登录
			if (!ftp.login(username, password)) {
				throw new AppException("帐号或密码错误,登录FTP失败!");
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
			ftp.enterLocalPassiveMode();

			if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
				ftp.disconnect();
				throw new AppException("连接FTP服务失败!");
			}
			if (!ftp.changeWorkingDirectory(remotePath)) {
				throw new AppException("FTP工作目录未找到!!");
			}

			FTPFile[] fs = ftp.listFiles(checkFile);

			if (fs == null || fs.length < 1) {

				throw new AppException("检验文件不存在!");
			}

			boolean checkstatus = false;

			for (int i = 0; i < fs.length; i++) {
				if (fs[i].getName().equals(checkFile)) {
					checkstatus = true;
				}
			}

			if (!checkstatus) {
				throw new AppException("检验文件不存在!");
			}

			fs = ftp.listFiles(fileName);

			if (fs == null || fs.length < 1) {
				throw new AppException("目标文件不存在!");
			}
			checkstatus = false;
			for (int i = 0; i < fs.length; i++) {
				if (fs[i].getName().equals(fileName)) {
					checkstatus = true;
				}
			}
			if (!checkstatus) {
				throw new AppException("目标文件不存在!");
			}

			File localFile = new File(localFTPPath + "/" + fileName);
			outputStream = new FileOutputStream(localFile);
			ftp.retrieveFile(fileName, outputStream);
			outputStream.close();

		} catch (Exception e) {
			e.printStackTrace();
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			throw new AppException(e.getMessage());
		} finally {

			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				ftp.logout();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * 解析文件
	 * 
	 * @return
	 */
	/*
	 * //add ..,String fileName) before (InputStream is,String separator)
	 * private static List<String[]> analyzeData(InputStream is, String
	 * separator,String fileName)throws AppException{
	 * 
	 * BufferedReader reader = null;
	 * 
	 * List<String[]> list = new ArrayList<String[]>();
	 * 
	 * try {
	 * 
	 * reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
	 * 
	 * String tempString = null; int count = 0; while ((tempString =
	 * reader.readLine()) != null){ System.out.println(tempString); tempString =
	 * tempString + ",,,"; list.add(tempString.replaceAll("null",
	 * "").split("\\"+separator)); count ++; } for(int i = 0;i<list.size();i++){
	 * String [] tem =list.get(i); list.get(i)[tem.length-3] = fileName;
	 * list.get(i)[tem.length-2] = i+""; list.get(i)[tem.length-1] =
	 * list.size()+""; }
	 * 
	 * return list; }catch (Exception e){ e.printStackTrace(); throw new
	 * AppException(e.getMessage()); } }
	 */

}
